import { _decorator, Animation, AudioClip, Collider2D, Component, Contact2DType, Node, Sprite, view } from "cc";
import { SetBasicInfo } from "../Utils/SetBasicInfo";
import { Bullet } from "./Bullet";
import { GameManager } from "./GameManager";
import { EnemyManager } from "./EnemyManager";
import { AudioMgr } from "./AudioMgr";
const { ccclass, property } = _decorator;

@ccclass("Enemy")
export class Enemy extends Component {
  // 屏幕宽高
  pageWidth: number = 0;
  pageHeight: number = 0;

  @property
  speed: number = 300;

  @property(Animation)
  anim: Animation = null;

  @property
  hp: number = 1;

  @property
  animHit: string = "";

  @property
  animDown: string = "";

  // 分数
  @property
  score: number = 100;

  @property(AudioClip)
  enemyDownAudio: AudioClip = null;

  collider: Collider2D = null;

  protected start(): void {
    this.getBgHeight();
    const collider = this.getComponent(Collider2D);
    this.collider = collider;
    this.collider?.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
  }

  update(deltaTime: number) {
    const position = this.node.position;
    if (this.hp > 0) {
      SetBasicInfo.setPosition(this.node, {
        y: position.y - this.speed * deltaTime,
      });
    }

    if (position.y < -this.pageHeight) {
      this.node?.destroy();
    }
  }

  /**
   * 获取背景高度
   */
  getBgHeight() {
    const { width, height } = view.getVisibleSize();
    this.pageWidth = width;
    this.pageHeight = height;
  }

  protected onDestroy(): void {
    this.collider?.off(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);

    EnemyManager.getInstance().removeEnemy(this.node);
  }

  onBeginContact(_selfCollider: Collider2D, otherCollider: Collider2D) {
    // 如果碰撞体是子弹
    if (otherCollider.getComponent(Bullet)) {
      // 禁用碰撞
      otherCollider.enabled = false;
      otherCollider.getComponent(Sprite).enabled = false;
    }
    this.hp -= 1;
    // 敌人未死亡时运行hit动画，死亡时播放down动画
    if (this.hp > 0) {
      this.anim.play(this.animHit);
    } else {
      this.anim.play(this.animDown);
    }

    if (this.hp <= 0) this.dead();
  }

  haveDead: boolean = false;
  dead() {
    if (this.haveDead) return;
    AudioMgr.inst.playOneShot(this.enemyDownAudio, 1);
    EnemyManager.getInstance().removeEnemy(this.node);
    // 当前敌人死亡
    GameManager.getInstance().AddSocre(this.score);
    // 禁用碰撞
    this.collider && (this.collider.enabled = false);
    // 等待一秒动画播放完毕后销毁
    this.scheduleOnce(() => {
      this.node.destroy();
    }, 1);
    this.haveDead = true
  }

  killNow() {
    if (this.hp <= 0) return;
    this.hp = 0;
    this.anim.play(this.animDown);
    this.dead();
  }
}
